<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { getAnnouncementList, initSocket, onNewAnnouncement, offNewAnnouncement } from '../api/auth'
import { ElNotification } from 'element-plus'

const announcements = ref<any[]>([])


// 获取用户信息
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

const fetchAnnouncements = async () => {
  try {
    const res = await getAnnouncementList({ page: 1, size: 5 })
    if (res.data.code === 200 && res.data.data.length > 0) {
      announcements.value = res.data.data
    }
  } catch (e) {}
}

onMounted(() => {
  fetchAnnouncements()
  
  // 初始化 Socket.IO 连接并监听新公告
  if (userInfo._id) {
    initSocket(userInfo._id)
    
    // 监听新公告事件
    onNewAnnouncement((data: any) => {
      // 将新公告添加到列表开头
      announcements.value.unshift(data.announcement)
      
      // 如果模态框没有显示，则显示它
      if (!showAnnouncementDialog.value) {
        showAnnouncementDialog.value = true
      }
      
      // 显示通知
      ElNotification({
        title: '新公告',
        message: data.message,
        type: 'info',
        duration: 5000
      })
    })
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  offNewAnnouncement()
})
</script>

<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <div class="dashboard-title">首页</div>
      <div class="dashboard-welcome">欢迎回来，商户</div>
    </div>
    <div v-if="announcements.length > 0" class="announcement-list" style="margin-bottom: 24px;">
      <el-row :gutter="0">
        <el-col :span="24" v-for="item in announcements.filter(a => a.status === '已发布')" :key="item._id" style="margin-bottom: 16px;">
          <el-card>
            <div class="announcement-title">{{ item.title }}</div>
            <div style="color:#888;">{{ item.content }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="dashboard-stats">
      <el-card v-for="item in stats" :key="item.title" class="stat-card">
        <div class="stat-title">{{ item.title }}</div>
        <div class="stat-value" :style="{ color: item.color }">
          <span class="stat-icon"><i :class="item.icon"></i></span>
          <span style="font-size:2rem;font-weight:bold;">{{ item.value }}</span>
          <span class="stat-unit">{{ item.unit }}</span>
        </div>
        <div class="stat-sub">{{ item.sub }}</div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.announcement-title {
  font-size: 1.1rem;
  font-weight: bold;
  margin-bottom: 8px;
}
</style> 